﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;

namespace SO.MyMoney
{
    public class Globals
    {
        public static bool IsMultiTenant
        {
            get
            {
                return HasMultipleTenants();
            }
        }

        public static string GetSettingValue(string settingId)
        {
            try
            {
                SPList list = SPContext.Current.Web.Lists.TryGetList(Definitions.SETTING_LIST);
                if (list != null)
                {
                    string queryString = string.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>",
                        settingId);
                    SPQuery query = new SPQuery();
                    query.Query = queryString;

                    SPListItemCollection items = list.GetItems(query);
                    if (items.Count > 0)
                    {
                        return items[0][Definitions.FIELD_SETTING_VALUE].ToString();
                    }
                    else
                    {
                        return string.Empty;
                    }
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        private static bool HasMultipleTenants()
        {
            try
            {
                SPList list = SPContext.Current.Web.Lists.TryGetList(Definitions.BOOKING_MANDATORY_LIST);
                if (list != null)
                {
                    if (list.Items.Count == 0)
                    {
                        throw new Exception("No mandatories defined!");
                    }
                    else if (list.Items.Count == 1)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    throw new Exception("No mandatory list found");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error while checking Multi-Tenancy", ex);
            }
        }

        public static SPListItemCollection GetMandatories()
        {
            try
            {
                string queryString = string.Format("<OrderBy><FieldRef Name='Title' /></OrderBy>");

                SPQuery query = new SPQuery();
                query.Query = queryString;

                return SPContext.Current.Web.Lists[Definitions.BOOKING_MANDATORY_LIST].GetItems(query);
            }
            catch (Exception ex)
            {
                throw new Exception("Error retrieving mandatories", ex);
            }
        }

        public static SPListItem GetMandatoryByMandatoryNumber(int mandatory)
        {
            try
            {
                string queryString = string.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Integer'>{1}</Value></Eq></Where>", Definitions.FIELD_MANDATORY_NUMBER,
                    mandatory);
                SPQuery query = new SPQuery();
                query.Query = queryString;

                SPListItemCollection items = SPContext.Current.Web.Lists[Definitions.BOOKING_MANDATORY_LIST].GetItems(query);

                if (items.Count > 1)
                {
                    throw new ArgumentException("Too many mandatories found");
                }
                else if (items.Count == 1)
                {
                    return items[0];
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error retireving mandatory", ex);
            }
        }

        public static bool MandatoryHasCurrentPeriod(int mandatory)
        {
            try
            {
                SPListItem item = GetMandatoryByMandatoryNumber(mandatory);

                if (item != null)
                {
                    int temp =0;
                    return int.TryParse(item[Definitions.FIELD_MANDATORY_CURPER].ToString(), out temp);
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public static int GetCurrentPeriodByMandatory(int mandatory)
        {
            try
            {
                SPListItem item = GetMandatoryByMandatoryNumber(mandatory);

                if (item != null)
                {
                    return int.Parse(item[Definitions.FIELD_MANDATORY_CURPER].ToString());
                }
                else
                {
                    throw new Exception("Unknown mandatory");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error retrieving current booking period by mandatory", ex);
            }
        }

        public static double GetCurrentBalance(int mandatory)
        {
            try
            {
                int currentPeriod = int.Parse(GetSettingValue(Definitions.SETTING_CURR_PERIOD));
                
                SPListItemCollection items = GetBookingsByPeriod(currentPeriod, mandatory);

                double balance = 0;
                foreach (SPListItem item in items)
                {
                    balance += double.Parse(item[Definitions.FIELD_BOOKING_AMOUNT].ToString());
                }

                return balance;
            }
            catch (Exception ex)
            {
                throw new Exception("Error retireving current balance", ex);
            }
        }

        public static SPListItemCollection GetBookingsByPeriod(int period, int mandatory)
        {
            try
            {
                SPList list = SPContext.Current.Web.Lists.TryGetList(Definitions.BOOKING_LIST);
                if (list != null)
                {
                    string queryString = string.Format("<Where><And><Eq><FieldRef Name='{0}' /><Value Type='Integer'>{1}</Value></Eq><Eq><FieldRef Name='{2}' /><Value Type='Integer'>{3}</Value></Eq></And></Where>", 
                        Definitions.FIELD_BOOKING_PERIOD, period.ToString(), Definitions.FIELD_BOOKING_MANDATORY, mandatory.ToString());
                    SPQuery query = new SPQuery();
                    query.Query = queryString;

                    return list.GetItems(query);
                }
                else
                {
                    throw new Exception("No booking list found");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error while loading bookings by period", ex);
            }
        }

        public static string GetAccountType(int id)
        {
            try
            {
                SPList list = SPContext.Current.Web.Lists.TryGetList(Definitions.BOOKING_ACCOUNT_LIST);
                if (list != null)
                {
                    SPListItem item = list.GetItemById(id);
                    if (item != null)
                    {
                        return item[Definitions.FIELD_ACCOUNT_TYPE].ToString();
                    }
                    else
                    {
                        throw new Exception("Account information not found");
                    }
                }
                else
                {
                    throw new Exception("No account list found");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error getting account type", ex);
            }
        }
    }
}
